package mqigdcom.mqigd.ui;

import android.graphics.Rect;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

/**
 * 解决WebView键盘遮挡问题
 */
class WebKeyboardListener {

    private ViewGroup rootContainer;
    private int statusBarVisibleHeight;// 状态栏的可见高度
    private int usableHeightPrevious;// 之前可用的显示高度
    private ViewGroup.LayoutParams containerParams;
    private boolean flagResizeView;// 重置布局尺寸的标识。true 可以重置；false 警用

    WebKeyboardListener(ViewGroup rootContainer, int statusBarVisibleHeight) {
        this.rootContainer = rootContainer;
        this.statusBarVisibleHeight = statusBarVisibleHeight;
    }

    /**
     * 初始化
     */
    public void init() {
        rootContainer.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    public void onGlobalLayout() {
                        possiblyResizeContentView();
                    }
                });
        containerParams = rootContainer.getLayoutParams();
    }

    /**
     * 启用内容布局的尺寸重置
     */
    public void enableResizeView() {
        flagResizeView = true;
    }

    /**
     * 禁用内容布局的尺寸重置
     */
    public void disableResizeView() {
        flagResizeView = false;
    }

    /**
     * 内容布局的尺寸重置
     */
    private void possiblyResizeContentView() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            usableHeightPrevious = usableHeightNow;
            int windowHeight = rootContainer.getHeight();
            int heightDifference = windowHeight - usableHeightNow - statusBarVisibleHeight;
            if (Math.abs(heightDifference) > windowHeight / 4.0f) {// 软键盘的高度
                if (flagResizeView) {
                    containerParams.height = windowHeight - heightDifference;
                }
                rootContainer.requestLayout();
                return;
            }
            if (Math.abs(heightDifference) > 100) {// 底部导航条的高度
                containerParams.height = windowHeight - heightDifference;
            } else {
                containerParams.height = windowHeight;
            }
            rootContainer.requestLayout();
        }
    }

    /**
     * 计算可用的高度
     *
     * @return 高度值
     */
    private int computeUsableHeight() {
        Rect r = new Rect();
        rootContainer.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }
}
